#include "avformat.h"
#include "internal.h"
#include "network.h"
#include "os_support.h"
#include "url.h"
#include "tls.h"
#include "libavcodec/internal.h"
#include "libavutil/avstring.h"
#include "libavutil/avutil.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "libavutil/thread.h"

#include <emscripten.h>
#include <emscripten/fetch.h>

#include <math.h>

#include "FFmpegExtra/Downloader_C.h"

#define min(x,y)  ( x<y?x:y )

typedef struct EyerWASMHTTPContext
{
    void * downloader;
    int pos;
} EyerWASMHTTPContext;

static int eyer_wasm_http_open(URLContext *h, const char *filename, int flags, AVDictionary ** option)
{
    EyerWASMHTTPContext * c = h->priv_data;
    c->pos = 0;
    c->downloader = WASM_Ext_GetDownloader(filename + 11);
    WASM_Ext_Downloader_Open(c->downloader);
    return 0;
}

static int eyer_wasm_http_read(URLContext *h, uint8_t *buf, int size)
{
    EyerWASMHTTPContext * c = h->priv_data;
    int len = WASM_Ext_Downloader_Read(c->downloader, buf, size, c->pos);
    if(len == -1){
        return AVERROR_EOF;
    }
    c->pos += len;
    return len;
}

static int eyer_wasm_http_close(URLContext *h)
{
    EyerWASMHTTPContext * c = h->priv_data;
    if(c->downloader != NULL){
        WASM_Ext_Downloader_Close(c->downloader);
        c->downloader = NULL;
    }
    return 0;
}

static int64_t eyer_wasm_http_seek(URLContext *h, int64_t off, int whence)
{
    // printf("Redknot eyer_wasm_http_seek\n");
    return 0;
}

const URLProtocol ff_eyerwasmhttp_protocol = {
    .name                = "wasmhttp",
    .url_open2           = eyer_wasm_http_open,
    .url_read            = eyer_wasm_http_read,
    .url_close           = eyer_wasm_http_close,
    .url_seek            = eyer_wasm_http_seek,
    .priv_data_size      = sizeof(EyerWASMHTTPContext),
    .flags               = URL_PROTOCOL_FLAG_NETWORK
};